package demo;

import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.example.tianjin.heyilianchuang.chali.calculator20231122.box_heyi_20231122.R;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.Toaster;
import com.orhanobut.logger.Logger;
import com.xls.boxlibrary.WithdrawalUtil;
import com.xls.boxlibrary.dilog.JiFenDialog;
import com.xls.boxlibrary.risk.RiskEncodeUtil;
import com.xls.boxlibrary.statusbar.StatusBarUtil;
import com.xls.boxlibrary.utils.AppUtils;
import com.xls.boxlibrary.utils.TUtils;
import com.xls.commonlibrary.BuildConfig;
import com.xls.commonlibrary.ad.adn.gm.GMBannerUtil;
import com.xls.commonlibrary.ad.adn.gm.GMFullUtil;
import com.xls.commonlibrary.ad.adn.reward.util.PointUtil;
import com.xls.commonlibrary.ad.adn.reward.util.ShowRewardAdsUtil;
import com.xls.commonlibrary.arouter.provider.IBizProvider;
import com.xls.commonlibrary.bean.ShowEcpmResult;
import com.xls.commonlibrary.bean.UserGameInfo;
import com.xls.commonlibrary.http.CallbackT;
import com.xls.commonlibrary.http.RxLifecycle;
import com.xls.commonlibrary.http.Transformer;
import com.xls.commonlibrary.http.biz.CodeRewardUtil;
import com.xls.commonlibrary.http.biz.HeartUtil;
import com.xls.commonlibrary.http.biz.UserUtil;
import com.xls.commonlibrary.ui.dialog.TimerDialog;
import com.xls.commonlibrary.util.ICallback;
import com.xls.commonlibrary.util.LoginUtil;
import com.xls.commonlibrary.util.LogoutUtil;
import com.xls.commonlibrary.util.MMKVUtil;
import com.xls.commonlibrary.util.TokenUtil;
import com.xls.commonlibrary.util.dislogx.DialogXUtil;
import com.xls.commonlibrary.util.eventbus.MessageEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import androidx.appcompat.app.AppCompatActivity;
import io.reactivex.rxjava3.core.Observable;

import static com.xls.commonlibrary.arouter.path.APath.BIZ_IBIZPROVIDERIMPL;
import static com.xls.commonlibrary.arouter.path.APath.DDX_GAME;
import static com.xls.commonlibrary.constant.Const.GAME_GOTO_JIFEN;
import static com.xls.commonlibrary.constant.Const.GAME_SHOW_AD;
import static com.xls.commonlibrary.constant.Const.MMKV_IS_UPDATE_GAME;



@Route(path = DDX_GAME)
public class GameDdxActivity extends AppCompatActivity {


    // ddx call biz's
    @Autowired(name = BIZ_IBIZPROVIDERIMPL)
    IBizProvider iBizProvider = null;

    private FrameLayout mBannerContainer; // banner广告容器view
    public WebView mWebView;
    public static SplashDialog mSplashDialog;
    public static TipDialog tipDialog;
    /**
     *  展示广告
     */
    void showAd() {
//       广告获取中弹窗
        DialogXUtil.showLoading();

        ShowRewardAdsUtil.getInstance().showAdGM(this, transId -> {

            if (TextUtils.isEmpty(transId)) {
                DialogXUtil.closeLoading();
                return;
            }
//            获取积分
            getPoints(true, transId);
        });

//        if (TokenUtil.getInstance().getGameType()){
//            ShowRewardAdsUtil.getInstance().showAdGM(this, transId -> {
//
//                if (TextUtils.isEmpty(transId)) {
//                    return;
//                }
////            获取积分
//                getPoints(true, transId);
//            });
//        }else {
//            //        半屏广告
//            GMFullUtil.getInstance().showAd(this, true, result -> {
////            激励广告
//                ShowRewardAdsUtil.getInstance().showAdGM(this, transId -> {
//
//                    if (TextUtils.isEmpty(transId)) {
//                        return;
//                    }
////            获取积分
//                    getPoints(true, transId);
//                });
//
//            });
//        }
    }


    /**
     * 风控检测-权限获取
      */
    void riskCheck(ICallback callback, String status) {

        XXPermissions.with(GameDdxActivity.this)
                .permission(Permission.READ_EXTERNAL_STORAGE)
                .permission(Permission.WRITE_EXTERNAL_STORAGE)
//                .permission(Permission.READ_PHONE_NUMBERS)
//                .permission(Permission.READ_PHONE_STATE)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            LoginUtil.getInstance().getLoginParams2(GameDdxActivity.this, new CallbackT<Map<String, String>>() {
                                @Override
                                public void callback(Map<String, String> stringStringMap) {
//                                    stringStringMap.put("appName", AppUtils.getPackageName(activity));
//                                        stringStringMap.put("token", SPUtils.getLoginToken(context));
//                                        fkCheck(stringStringMap,score,finalScore);
                                    riskGet(callback, stringStringMap, status);
                                }
                            });
                        }else {
                            TUtils.showShort(GameDdxActivity.this, "请您前往设置授予应用权限，否则无法观看视频 k");
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            XXPermissions.startPermissionActivity(GameDdxActivity.this, permissions);
                        } else {
                            TUtils.showShort(GameDdxActivity.this, "请授予权限后，重新登陆 k");
                            LoginUtil.getInstance().outLogin(GameDdxActivity.this);
                        }
                    }
                });


    }

    /**
     * 风控检测
     * @param callback
     * @param map
     * @param status
     */
    void riskGet(ICallback callback, Map<String, String> map, String status) {
        RiskEncodeUtil.getInstance().riskCheck(GameDdxActivity.this, status, map,
                result -> {

                    int code = result.getCode();
                    Logger.d("========risk=============code====" + code);
                    Logger.d("========risk=============code====" + result.getMsg());
                    if (code != 1) {
                        DialogXUtil.closeLoading();
                    }

                    if (code == 1) {
                        if (!TextUtils.isEmpty(result.getMsg())){
                            Toaster.show(result.getMsg());
                        }
                        // 风控通过
                        if (null != callback) {
                            callback.callback();
                        }
                    } else if (code == 2) {
                        if (!TextUtils.isEmpty(result.getMsg())){
                            Toaster.show(result.getMsg());
                        }else {
                            Toaster.show("手机太累了，该休息休息了");
                        }
                    } else if (code == 3) {
                        // 退出登陆清空缓存，清空栈,进入登陆页面
                        // 登陆失败 清空旧用户缓存
                        LogoutUtil.clearCache();

                        // 进登陆页
//                        Intent intent = new Intent(MainActivity.this, HomeActivity.class);
//                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        startActivity(intent);


                        finish();
                    } else {
                        Toaster.show(result.getMsg());
                    }
                });
    }


    void showPointDialog(ShowEcpmResult info) { // 积分弹框
//        void showPointDialog(String left, String right) { // 积分弹框

        JiFenDialog dialog = new JiFenDialog(this,
                info,0,
                result -> {
                    if ("-1".equals(result)) {
                        DialogXUtil.closeLoading();
                        updateGameUser();

                        // 直接收下
//                        GMFullUtil.getInstance().showAd(this, true, back -> {
//                        });
                    } else {
                        // 我要翻倍 点击事件
                        showAd();
                        riskCheck(() -> {
                            showAd();
                        }, "game_ad_get");
                    }
                });

        Logger.d("======showPointDialog=====showDialog======");
        dialog.show();

        GMFullUtil.getInstance().showAd(this, true, result -> {
        });
//        TimerDialog.newInstance(GameDdxActivity.this).show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event == null) {
            return;
        }
        Logger.d(event);
        if (GAME_SHOW_AD.equals(event.getCode())) {
//            展示广告流程
//            riskCheck(() -> {
                showAd();
//            }, "game_ad_get");

        } else if (GAME_GOTO_JIFEN.equals(event.getCode())) {
            WithdrawalUtil.getInstance()
                    .startWithdrawalActivity(this, BuildConfig.APPID, AppUtils.getPackageName(this));
        }
    }

    /**
     * 激励视频看完给予奖励
     */
    void updateGameUser() {
        if (TextUtils.equals(BuildConfig.GAME_TYPE,"xxl")||TokenUtil.getInstance().getGameType()){
            // JS:费劲还得这么判断
            UserGameInfo info = LoginUtil.getInstance().getUser();
            if (info == null) {
                return;
            }
            Logger.d("===========updateGameUser======更新游戏用户信息======");
//        Toaster.show("===========updateGameUser======更新游戏用户信息======");

            // 通知游戏更新积分
            UserUtil.getInstance().getUserGameAccount(this, bk -> {
                if (bk) {
                    JSBridge.notifyUpdateMoney(true, "ok");
                    JSBridge.updateData();
                }
            });
        }else {
            JSBridge.closeAppVideoViewADCallBack(true, "ok");
            if(TextUtils.equals(BuildConfig.GAME_TYPE,"dy")){
                JSBridge.closeMusic();
                JSBridge.openMusic();
            }
            if (TextUtils.equals(BuildConfig.GAME_TYPE,"cy")){
                JSBridge.updateData();
            }
        }
    }

    boolean isPop = false;

    /**
     * 获取积分展示
     * @param pop
     * @param transId
     */
    void getPoints(boolean pop, String transId) {
        isPop = pop;
        PointUtil.getInstance().getPoints(transId, this, result -> {
            if (isPop) {
                showPointDialog(result);
            }else {
                DialogXUtil.closeLoading();
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // important!!
        ARouter.getInstance().inject(this);

        EventBus.getDefault().register(this);

        JSBridge.mMainActivity = this;

        setContentView(R.layout.activity_game);
        mSplashDialog = new SplashDialog(this);
        tipDialog=new TipDialog(this);
        tipDialog.showSplash();
//        mSplashDialog.showSplash();

        if (TextUtils.equals(BuildConfig.GAME_TYPE,"xxl")||TokenUtil.getInstance().getGameType()||TextUtils.equals(BuildConfig.GAME_TYPE,"dy")){
//
        }else{
//            消消乐类，钓鱼类，无法全屏，关怀版伟消消乐类，也无法全屏
            setViewNOTitle();
        }
        initView();



        // 初始化积分
//        getPoints(false);


//         intervalGetBanner();

        // banner ad
//        GMBannerUtil.getInstance().loadBanner(this,
//                mBannerContainer,
//                value -> {
//
//                }
//        );

//         showBanner();

        // test dialog
        // showPointDialog("+290", "+40");

        UserUtil.getInstance().getUserGameAccount(this, result -> {
            if (result) {
                // 直接加载游戏
//                initEngine();
            }
        });

        // test
        // UserUtil.getInstance().updateUserGameAccount(this, "2", result -> {});

        initEngine();



        // test
        // updateGameUser();


        // preload reward ad
        CodeRewardUtil.getInstance().preloadAd(this);


        heartBeatInterval();

    }

    /**
     * 全屏展示
     */
    private void setViewNOTitle() {
        /*
         *  当FitsSystemWindows设置 true 时，会在屏幕最上方预留出状态栏高度的 padding
         */
        StatusBarUtil.setRootViewFitsSystemWindows(this,true);
        /*
         * 设置状态栏透明
         */
        StatusBarUtil.setTranslucentStatus(this);
        /*
         *一般的手机的状态栏文字和图标都是白色的, 可如果你的应用也是纯白色的, 或导致状态栏文字看不清
         *所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
         */
        if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
             /*如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
             这样半透明+白=灰, 状态栏的文字能看得清
             */
            StatusBarUtil.setStatusBarColor(this,0x55000000);
        }
        StatusBarUtil.setRootViewFitsSystemWindows(this,false);
    }


    /**
     * 心跳
     */
    boolean isResumed = true;
    void heartBeat() {

        Logger.d("=======heartBeat======isResumed=======%s=",isResumed);
        if (!isResumed){
            return;
        }

        HeartUtil.getInstance().userHeartbeat(GameDdxActivity.this, result -> {

        });
    }

    @SuppressLint("CheckResult")
    void heartBeatInterval() {

        // 定时任务  心跳

        Observable.interval(1, 60, TimeUnit.SECONDS)
                .compose(Transformer.transform())
                .compose(RxLifecycle.bindRxLifecycle(GameDdxActivity.this))
                .subscribe(aLong -> {
                    Logger.d("==========interval===onNext======heartBeat===序列号:" + aLong);
                    heartBeat();
                });
    }

    /**
     * 显示bannner
     */
    void showBanner() {
        GMBannerUtil.getInstance().loadBanner(this,
                mBannerContainer,
                value -> {

                }
        );
    }



    void initView() {
        // banner广告容器
        mBannerContainer = findViewById(R.id.banner_container);
        mWebView=findViewById(R.id.rl_webview);
    }

    public void initEngine() {
        JSBridge.webView = mWebView;
        WebSettings settings = mWebView.getSettings(); //和系统webview一样
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setSupportZoom(false);
        settings.setBuiltInZoomControls(false);
        settings.setDisplayZoomControls(false);
        settings.setJavaScriptEnabled(true); //支持Javascript 与js交互
        settings.setDomStorageEnabled(true);//支持持久化存储
        mWebView.setWebViewClient(new WebViewClient() {});
        try {
            if (TokenUtil.getInstance().getGameType()&&!TextUtils.isEmpty(com.xls.commonlibrary.util.AppUtils.getGuanHuaiURL(this))){
                mWebView.loadUrl(com.xls.commonlibrary.util.AppUtils.getGuanHuaiURL(this));
            }else{
                mWebView.loadUrl(BuildConfig.BASE_COM_URL_GAME);
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            mWebView.loadUrl(BuildConfig.BASE_COM_URL_GAME);
        }
        mWebView.setClickable(true);
        mWebView.addJavascriptInterface(new JSBridge(), "AndroidWebView");
    }



    protected void onPause() {
        super.onPause();
        isResumed = false;
        mWebView.onPause();
    }


    @Override
    protected void onStop() {
        super.onStop();
        isResumed = false;
    }
    boolean isStartBannner=false;
    //------------------------------------------------------------------------------
    protected void onResume() {
        super.onResume();
        mWebView.onResume();
        Logger.d("=====MainActivity=====onResume========getPoints========");

        // js里面处理积分的业务
//        getPoints(false);
        if (!isStartBannner){
            isStartBannner=true;
            showBanner();
        }

//        SigmobFullUtil.getInstance().showAd(this, result -> {});

        // 通知js刷新积分
//        ConchJNI.RunJS("UIAddDiamondCtl.getAndroidUpdateEcpm()");

        // todo  需要改为 iprovider来调用
        if (MMKVUtil.getInstance().getKV().decodeBool(MMKV_IS_UPDATE_GAME, false)) {
            MMKVUtil.getInstance().getKV().encode(MMKV_IS_UPDATE_GAME, false);
//            updateGameUser();
            if (TextUtils.equals(BuildConfig.GAME_TYPE,"xxl")||TokenUtil.getInstance().getGameType()){
                // 更新数据后，，通知游戏更新积分
                UserUtil.getInstance().getUserGameAccount(this, bk -> {
                    if (bk) {
                        JSBridge.updateData();
                    }
                });
            }
            else {
                JSBridge.updateData();
                if(TextUtils.equals(BuildConfig.GAME_TYPE,"dy")){
                    JSBridge.closeMusic();
                    JSBridge.openMusic();
                }
            }
        }

        riskCheck(null, "status_update");

    }

    protected void onDestroy() {
        super.onDestroy();

        isResumed = false;

        EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}
